<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能家居系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 更换为 Font Awesome 6 版本的 CDN 链接 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" integrity="sha512-z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbbKuqLg0DA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#0FC6C2',
                        warning: '#FF7D00',
                        success: '#00B42A',
                        danger: '#F53F3F',
                        info: '#86909C',
                        dark: '#1D2129',
                        light: '#F2F3F5'
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 4px 20px rgba(0, 0, 0, 0.08)',
                        'card-hover': '0 8px 30px rgba(0, 0, 0, 0.12)',
                    }
                },
            }
        }
    </script>
    <style>
        @layer utilities {
            .data-value {
                @apply text-[clamp(2rem,5vw,3.5rem)] font-bold transition-all duration-500;
            }
            .light-toggle {
                @apply w-20 h-10 rounded-full relative transition-all duration-300 cursor-pointer;
            }
            .light-toggle-circle {
                @apply absolute w-8 h-8 rounded-full bg-white shadow-md transition-all duration-300 top-1 left-1;
            }
            .animate-pulse-slow {
                animation: pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite;
            }
            .light-level {
                width: 20px;
                height: 20px;
                border-radius: 4px;
                background-color: #E5E7EB; /* 灰色 */
            }
            .light-level-active-1 {
                background-color: #FEF3C7;
            }
            .light-level-active-2 {
                background-color: #FDE68A;
            }
            .light-level-active-3 {
                background-color: #FCD34D;
            }
            .light-level-active-4 {
                background-color: #FBBF24;
            }
            .light-level-active-5 {
                background-color: #F59E0B;
            }
            .light-level-active-6 {
                background-color: #D97706;
            }
            .light-level-active-7 {
                background-color: #B45309;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-inter text-dark min-h-screen">
<div class="max-w-6xl mx-auto px-4 py-8">
    <header class="text-center mb-10">
        <h1 class="text-[clamp(1.8rem,4vw,2.5rem)] font-bold text-primary mb-2">智能家居系统</h1>
        <p class="text-gray-600">实时监控环境数据并控制设备</p>
    </header>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
        <!-- 温度显示卡片 -->
        <div class="bg-white rounded-xl p-6 shadow-card hover:shadow-card-hover transition-all duration-300 transform hover:-translate-y-1">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-xl font-semibold text-gray-700">温度</h2>
                <div class="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
                    <!-- 更换为 Font Awesome 6 的图标类名 -->
                    <i class="fa-solid fa-temperature-half text-red-500 text-xl"></i>
                </div>
            </div>
            <div class="flex items-end justify-between">
                <div>
                    <span id="temperature" class="data-value text-red-500">--</span>
                    <span class="text-xl text-gray-500 ml-1">°C</span>
                </div>
                <div class="text-sm text-gray-500">
                    <span id="temp-time">--</span>
                </div>
            </div>
            <div class="mt-4 h-2 bg-gray-100 rounded-full overflow-hidden">
                <div id="temp-progress" class="h-full bg-red-400 rounded-full" style="width: 0%"></div>
            </div>
        </div>

        <!-- 湿度显示卡片 -->
        <div class="bg-white rounded-xl p-6 shadow-card hover:shadow-card-hover transition-all duration-300 transform hover:-translate-y-1">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-xl font-semibold text-gray-700">湿度</h2>
                <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
                    <!-- 更换为 Font Awesome 6 的图标类名 -->
                    <i class="fa-solid fa-droplet text-blue-500 text-xl"></i>
                </div>
            </div>
            <div class="flex items-end justify-between">
                <div>
                    <span id="humidity" class="data-value text-blue-500">--</span>
                    <span class="text-xl text-gray-500 ml-1">%</span>
                </div>
                <div class="text-sm text-gray-500">
                    <span id="humidity-time">--</span>
                </div>
            </div>
            <div class="mt-4 h-2 bg-gray-100 rounded-full overflow-hidden">
                <div id="humidity-progress" class="h-full bg-blue-400 rounded-full" style="width: 0%"></div>
            </div>
        </div>

        <!-- 光照度显示卡片 -->
        <div class="bg-white rounded-xl p-6 shadow-card hover:shadow-card-hover transition-all duration-300 transform hover:-translate-y-1">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-xl font-semibold text-gray-700">光照等级</h2>
                <div class="w-10 h-10 rounded-full bg-yellow-100 flex items-center justify-center">
                    <!-- 更换为 Font Awesome 6 的图标类名 -->
                    <i class="fa-solid fa-sun text-yellow-500 text-xl"></i>
                </div>
            </div>
            <div class="flex items-end justify-between">
                <div>
                    <span id="light-level-display" class="data-value text-yellow-500">--</span>
                    <span class="text-xl text-gray-500 ml-1">级</span>
                </div>
                <div class="text-sm text-gray-500">
                    <span id="light-time">--</span>
                </div>
            </div>
            <!-- 添加光照等级显示 -->
            <div class="mt-4 flex space-x-2">
                <div class="light-level" id="light-level-1"></div>
                <div class="light-level" id="light-level-2"></div>
                <div class="light-level" id="light-level-3"></div>
                <div class="light-level" id="light-level-4"></div>
                <div class="light-level" id="light-level-5"></div>
                <div class="light-level" id="light-level-6"></div>
                <div class="light-level" id="light-level-7"></div>
            </div>
        </div>
    </div>

    <div class="bg-white rounded-xl p-6 shadow-card max-w-md mx-auto transition-all duration-500 transform hover:shadow-card-hover">
        <div class="flex flex-col items-center">
            <div class="w-24 h-24 mb-4 rounded-full bg-gray-100 flex items-center justify-center transition-all duration-500" id="light-icon-container">
                <!-- 更换为 Font Awesome 6 的图标类名 -->
                <i id="light-icon" class="fa-solid fa-lightbulb text-5xl text-gray-400 transition-all duration-500"></i>
            </div>
            <h2 class="text-xl font-semibold text-gray-700 mb-4">灯光控制</h2>
            <div class="mb-4">
                <div id="light-status" class="text-lg font-medium text-gray-500">灯状态: <span id="light-text">已关闭</span></div>
            </div>
            <button id="light-on-btn" class="bg-yellow-400 text-white px-4 py-2 rounded-md mr-2">开灯</button>
            <button id="light-off-btn" class="bg-gray-300 text-gray-700 px-4 py-2 rounded-md">关灯</button>
            <div class="mt-6 text-sm text-gray-500">
                <span id="light-action-time">最后操作: --</span>
            </div>
        </div>
    </div>
</div>

<script>
    // 模拟数据和配置
    const API_BASE_URL = 'http://8.137.18.32:8080/api';
    let lightStatus = 'off';

    // DOM 元素
    const temperatureEl = document.getElementById('temperature');
    const humidityEl = document.getElementById('humidity');
    const lightLevelDisplayEl = document.getElementById('light-level-display');
    const tempTimeEl = document.getElementById('temp-time');
    const humidityTimeEl = document.getElementById('humidity-time');
    const lightTimeEl = document.getElementById('light-time');
    const tempProgressEl = document.getElementById('temp-progress');
    const humidityProgressEl = document.getElementById('humidity-progress');
    const lightIcon = document.getElementById('light-icon');
    const lightIconContainer = document.getElementById('light-icon-container');
    const lightText = document.getElementById('light-text');
    const lightStatusEl = document.getElementById('light-status');
    const lightActionTimeEl = document.getElementById('light-action-time');
    const lightOnBtn = document.getElementById('light-on-btn');
    const lightOffBtn = document.getElementById('light-off-btn');

    // 更新时间戳显示
    function updateTimestamp(element) {
        const now = new Date();
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        element.textContent = `${hours}:${minutes}:${seconds}`;
    }

    // 更新进度条
    function updateProgressBar(element, value, maxValue) {
        const percentage = Math.min((value / maxValue) * 100, 100);
        element.style.width = `${percentage}%`;
        element.classList.add('animate-pulse-slow');
        setTimeout(() => {
            element.classList.remove('animate-pulse-slow');
        }, 1000);
    }

    // 更新灯光状态显示
    function updateLightStatus(status) {
        lightStatus = status;
        if (status === 'on') {
            lightIcon.classList.remove('text-gray-400');
            lightIcon.classList.add('text-yellow-300');
            lightIconContainer.classList.remove('bg-gray-100');
            lightIconContainer.classList.add('bg-yellow-50');
            lightText.textContent = '已开启';
            lightText.classList.remove('text-gray-500');
            lightText.classList.add('text-yellow-600');
            lightStatusEl.classList.add('text-yellow-600');
        } else {
            lightIcon.classList.remove('text-yellow-300');
            lightIcon.classList.add('text-gray-400');
            lightIconContainer.classList.remove('bg-yellow-50');
            lightIconContainer.classList.add('bg-gray-100');
            lightText.textContent = '已关闭';
            lightText.classList.remove('text-yellow-600');
            lightText.classList.add('text-gray-500');
            lightStatusEl.classList.remove('text-yellow-600');
        }
        updateTimestamp(lightActionTimeEl);
    }

    // 更新光照等级显示
    function updateLightLevel(resistance) {
        const maxResistance = 3167;
        const interval = Math.ceil(maxResistance / 7);
        const level = 7 - Math.min(Math.floor(resistance / interval), 6);

        for (let i = 1; i <= 7; i++) {
            const levelEl = document.getElementById(`light-level-${i}`);
            levelEl.className = 'light-level';
            if (i <= level) {
                levelEl.classList.add(`light-level-active-${i}`);
            }
        }
        return level;
    }

    function fetchSensorData() {
        fetch(`${API_BASE_URL}/sensors`)
            .then(response => response.json())
            .then(data => {
                // 更新温度显示
                temperatureEl.textContent = data.temperature.toFixed(1);
                updateTimestamp(tempTimeEl);
                updateProgressBar(tempProgressEl, data.temperature, 50);

                // 更新湿度显示
                humidityEl.textContent = data.humidity.toFixed(1);
                updateTimestamp(humidityTimeEl);
                updateProgressBar(humidityProgressEl, data.humidity, 100);

                // 更新光照等级显示
                const lightLevel = updateLightLevel(data.light);
                lightLevelDisplayEl.textContent = lightLevel;
                updateTimestamp(lightTimeEl);

                // 更新灯光状态
                updateLightStatus(data.lightStatus);
            })
            .catch(error => {
                console.error('获取传感器数据失败:', error);
                // 显示错误状态
                temperatureEl.textContent = '--';
                humidityEl.textContent = '--';
                lightLevelDisplayEl.textContent = '--';
            });
    }

    // 发送灯光控制命令
    function sendLightCommand(status) {
        fetch(`${API_BASE_URL}/light`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ status })
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateLightStatus(status);
                } else {
                    alert('操作失败，请重试');
                }
            })
            .catch(error => {
                console.error('发送灯光命令失败:', error);
                alert('网络错误，请检查连接');
            });
    }

    // 初始化
    function init() {
        // 初始获取一次数据
        fetchSensorData();

        // 设置定时获取数据
        setInterval(fetchSensorData, 5000);

        // 灯光控制按钮事件
        lightOnBtn.addEventListener('click', () => {
            sendLightCommand('on');
        });

        lightOffBtn.addEventListener('click', () => {
            sendLightCommand('off');
        });
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', init);
</script>
</body>
</html>